# 导入fastapi包
from fastapi import FastAPI, Request, Form
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
from tortoise.contrib.fastapi import register_tortoise  # 帮助app对象绑定要操作的函数
import uvicorn

from dao.models import Todo

app = FastAPI()
template = Jinja2Templates("pages")

# 初始化以后实现数据库的绑定
register_tortoise(app,
                  db_url="mysql://root:diding2014@localhost:3306/fastapi",
                  #      数据库类型://用户名:密码@ip:端口
                  modules={"models": ['dao.models']},  # 把数据库中的表 转化成python中的数据
                  generate_schemas=True,  # 生成结构
                  add_exception_handlers=True
                  )


#
# todos = ["qwq1", "qwq2", "qwq3"]


@app.get("/")
async def index(req: Request):
    # 使用ORM操作数据库，安全性提升，编程更加高效
    todos = await Todo.all()
    print("todos: ", todos)
    for todo in todos:
        print("todo.content:", todo.content)
    return template.TemplateResponse("index.html", context={"request": req, "todos": todos})


@app.post("/add_todo")
async def add_todo(content=Form(...)):
    """处理用户发过来的add into todolist 操作"""
    # todos.insert(0, todo)
    # instead, 我们需要把数据存在数据库当中

    await Todo(content=content).save()

    return RedirectResponse("/", status_code=302)


@app.post("/search")
async def search(req: Request, keyword=Form(...)):
    # 查询包含keyword的所有记录
    search_result = await Todo.filter(content__icontains=keyword).all()
    return template.TemplateResponse("search_result.html",
                                     context={"request": req, "search_results": search_result})


if __name__ == '__main__':
    uvicorn.run(app)
